package me.xuym.crawler.simpleextension.filter;

import com.cbs.java.component.application.Application;
import com.cbs.java.component.database.mysql.MySqlDatabase;

import java.io.IOException;
import java.util.Map;

/**
 * Created by broche on 09/09/2017.
 */
public class SimpleCachedMySQLListFilter extends SimpleCachedListFilter {
    private MySqlDatabase database;
    private String table;
    private boolean debug = false;

    public SimpleCachedMySQLListFilter(Application application, String host, String port, String username, String password, String database, String table) throws IOException, ClassNotFoundException {
        super(application);

        this.database = new MySqlDatabase(host, port, username, password, database);
        this.table = table;
    }

    public boolean isDebug() {
        return debug;
    }

    public SimpleCachedMySQLListFilter setDebug(boolean debug) {
        this.debug = debug;
        return this;
    }

    @Override
    protected boolean isCacheExisted(Map<String, String> fields) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("select count(1) from ")
                .append(table)
                .append(" where 1=1");
        for (String key : fields.keySet()) {
            stringBuilder.append(" and ").append(key)
                    .append("=")
                    .append("\"" + fields.get(key) + "\"");
        }
        long count = 0;
        try {
            if (isDebug()) {
                System.out.println(stringBuilder.toString());
            }
            count = database.scalar(stringBuilder.toString(), Long.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count > 0;
    }

    @Override
    protected void saveCache(Map<String, String> fields) {
        if (fields != null && !fields.isEmpty()) {
            StringBuilder keys = new StringBuilder();
            StringBuilder values = new StringBuilder();
            for (String key : fields.keySet()) {
                keys.append(key);
                keys.append(",");

                values.append("\"" + fields.get(key) + "\",");
            }
            keys.deleteCharAt(keys.length() - 1);
            values.deleteCharAt(values.length() - 1);

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("insert into ")
                    .append(table)
                    .append("(")
                    .append(keys)
                    .append(") values(")
                    .append(values)
                    .append(")");
            if (isDebug()) {
                System.out.println(stringBuilder.toString());
            }
            database.insert(stringBuilder.toString());
        }
    }
}
